package com.woniuxy.automotivemanagementsystem.utils.JWT;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.woniuxy.automotivemanagementsystem.entity.User;


import java.util.Date;

public class JwtUtil {
    public static final String SECRET_KEY = "woniuxy";
    /*密钥*/
    public static final long TOKEN_EXPIRE_TIME = 60 * 10000;
    /*过期时间*/
    public static final String ISSUER = "ISSUER";

    /*签发者*/
    /*
     *
     * 生成 token
     * */
    public static String createToken(User user) {
        Date now = new Date();
        //当前时间
        Algorithm algorithm = Algorithm.HMAC256(SECRET_KEY);
        //签名算法
        String token = JWT.create()
                .withIssuer(ISSUER)
                .withIssuedAt(now)
                .withExpiresAt(new Date(now.getTime() + TOKEN_EXPIRE_TIME))
                .withClaim("username", user.getUsername())
                .withClaim("id", user.getUid())
                .sign(algorithm);
        return token;
    }

    /*
     *
     * 验证 token
     * */
    public static TokenEnum verifyToken(String token) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(SECRET_KEY);
            JWTVerifier verifier = JWT.require(algorithm).withIssuer(ISSUER).build();
            verifier.verify(token);
            return TokenEnum.TOKENSUCCESS;//token有效
        } catch (TokenExpiredException e) {
            return TokenEnum.TOKENEXPIRE;//token过期
        } catch (Exception e) {
            return TokenEnum.TOKENINVALID;//token无效
        }
    }
    // 判断token是否过期
//    public static boolean isTokenExpired(String token) {
//
//        try{
//            //创建验证器对象
//            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET_KEY)).withIssuer(ISSUER).build();
//            //解码token
//            DecodedJWT jwt = verifier.verify(token);
//            //获取过期时间
//            Date expiresDate = jwt.getExpiresAt();
//            System.out.println("比较token是否过期:" + new Date().after(expiresDate));
//            //比较当前时间是否超过过期时间
//            return new Date().after(expiresDate);
//        }catch (Exception e){
//            //如果出现异常也被是为过期
//            e.printStackTrace();
//            return true;
//        }
//    }

    /**
     * 刷新token
     */
    public static String refresh(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            //获取用户名
            String username = jwt.getClaim("username").asString();
            Long id = jwt.getClaim("id").asLong();
            Algorithm algorithm = Algorithm.HMAC256(SECRET_KEY);
            Date now = new Date(); //最新时间
            Date expiresDate = new Date(now.getTime() + TOKEN_EXPIRE_TIME); //过期时间

            return JWT.create()
                    .withClaim("id", id)
                    .withClaim("username", username)
                    .withIssuedAt(now)
                    .withExpiresAt(expiresDate)
                    .sign(algorithm);
        } catch (JWTDecodeException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 从token获取uname
     */
    public static String getUsername(String token) {
        try {
            return JWT.decode(token).getClaim("username").asString();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return "";
    }

    /**
     * 从token获取uid值
     */
    public static Long getId(String token) {
        try {
            return JWT.decode(token).getClaim("id").asLong();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

    public static String generateToken(User user) {
        return createToken(user);
    }
}
